package com.gopay.bis.spdb.expay.operation;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.XMLBeanUtils;
import com.gopay.bis.spdb.ebank.operation.parse.Packet;
import com.gopay.common.domain.bank.spdb.expay.SpdbMessageExPay;
import com.gopay.remote.bank.ICertHelper;

/**
 * @SpdbExPaySignQueryParseMessage.java
 * @author w_jiqing
 * @2016年6月6日 上午10:59:10  www.gopay.com.cn Inc.All rights reserved.
 */
public class SpdbExPaySignQueryParseMessage {

    /** 验签实现类 */
    private ICertHelper spdbExPayCertHelper; 
    
    private static Log logger = LogFactory.getLog(SpdbExPaySignParseMessage.class);
    
    /**
     * @param receivedMsgData
     * @return
     */
    public SpdbMessageExPay parseSpdbMessage(Object receivedMsgData,SpdbMessageExPay message){
        String xmlMsg = (String) receivedMsgData;
        SpdbMessageExPay spdbMsg = new SpdbMessageExPay();
        BeanUtils.copyProperties(message, spdbMsg);
        try {
            @SuppressWarnings("rawtypes")
            Map<String, Class> cm = new HashMap<String, Class>();
            cm.put("packet", Packet.class);
            Packet pack = (Packet) XMLBeanUtils.xml2Bean(cm, xmlMsg);
            String plainMessage = pack.getPlain();
            String signMessage = pack.getSignature();
            if (plainMessage == null || "".equals(plainMessage) || signMessage == null ||  "".equals(signMessage)) {
                // 若明文和密文字段为空，则交易失败
                spdbMsg.setErrorCode(pack.getErrorCode());
                spdbMsg.setErrorMsg(pack.getErrorMsg());
            } else {
                // 若取得明文和密文字段，则进行验签
                spdbMsg.setPlainMessage(plainMessage);
                spdbMsg.setSignMessage(signMessage);
                if ((Boolean) this.spdbExPayCertHelper.verify(spdbMsg)) {
                    spdbMsg = getSignQueryMessageExpay(pack);
                } else {
                    throw new Exception("SPDB快捷支付签约查询结果验签失败！！");
                }
            }
        } catch (Exception ex) {
             logger.error("SPDB EXPAY sign query parse xml error:" + ex);
        }
        return spdbMsg;
    }
    
    /**
     * 根据解析出来的packet组装返回的SpdbMessageExpay
     * @param pack
     * @return
     */
    private SpdbMessageExPay getSignQueryMessageExpay(Packet pack){
        SpdbMessageExPay spdbMsg = new SpdbMessageExPay();
        Map plainMap = str2map(pack.getPlain());
        spdbMsg.setMercId((String)plainMap.get("Merc_id"));
        spdbMsg.setSignStatus((String)plainMap.get("SignStatus"));
        spdbMsg.setSignDate((String)plainMap.get("SignDate"));
        spdbMsg.setCloseDate((String)plainMap.get("CloseDate"));
        return spdbMsg;
    }
    
    /**
     * 解析明文放入Map.
     * 
     * @param dataStr
     * @return
     */
    private Map str2map(String dataStr) {
        if (dataStr == null || dataStr.length() == 0) {
            return null;
        }
        LinkedHashMap retMap = new LinkedHashMap();
        String terms[] = dataStr.split("\\|");
        int len = terms.length;
        for (int i = 0; i < len; i++) {
            String term = terms[i];
            int index = term.indexOf("=");
            retMap.put(term.substring(0, index), term.substring(index + 1));
        }

        return retMap;
    }

    public ICertHelper getSpdbExPayCertHelper() {
        return spdbExPayCertHelper;
    }

    public void setSpdbExPayCertHelper(ICertHelper spdbExPayCertHelper) {
        this.spdbExPayCertHelper = spdbExPayCertHelper;
    }


}
